//
//  CMFVerCodeCtrl.m
//  CreditManger
//
//  Created by 于会海 on 15/11/2.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMFVerCodeCtrl.h"
#import "CMFReSetPasswordCtrl.h"
#import "CMGetRegMobileCodeInfo.h"
#import "CMGetRegMobileCodeParam.h"
#import "CMGetRegMobileCodeParser.h"
#import "CMCheckPwdMobileCodeParam.h"
#import "CMCheckPwdMobileCodeParser.h"

@interface CMFVerCodeCtrl ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneCode;
@property (weak, nonatomic) IBOutlet UIButton *reGetBtn;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIButton *doBtn;
- (IBAction)reGetBtnClicked:(id)sender;
- (IBAction)doBtnClicted:(id)sender;

@end

@implementation CMFVerCodeCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (void)buildLayout{
    self.title = @"短信验证码";
    self.doBtn.layer.cornerRadius = 4.0;
    
    NSString* str = self.phoneNumber;
    NSString* string1 = [str substringToIndex:3];
    NSString* string2 = [str substringWithRange:NSMakeRange(3, 4)];
    NSString* string3 = [str substringWithRange:NSMakeRange(7, 4)];
    NSMutableString* string4  = [[NSMutableString alloc] initWithCapacity:13];
    [string4 appendFormat:@"请输入 \"%@ %@ %@\" 收到的短信验证码",string1,string2,string3];
    self.phoneLabel.text = string4;
    self.phoneCode.text = self.vercode;//在上线前取消
    self.phoneCode.delegate = self;
}

#pragma textField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"])
    {
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.phoneCode == textField) {
        if ([toBeString length] > 5)
        {
            textField.text = [toBeString substringToIndex:6];
            [textField resignFirstResponder];
            return NO;
        }
    }
    return YES;
}
- (void)doBack{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addGraph" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma  buttonClicked
- (IBAction)reGetBtnClicked:(UIButton *)sender {
    LLog(@"重新获取手机验证码");
    [self setTimeSynchronize];
    [self makeTime];
    CMGetRegMobileCodeParam* param = [[CMGetRegMobileCodeParam alloc] init];
    param.mobile = self.phoneNumber;
    param.gid = [self getGID];
    CMGetRegMobileCodeParser* parser = [[CMGetRegMobileCodeParser alloc] init];
    [NetCenter postDataFromURL:Method_getPwdMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            
            CMGetRegMobileCodeInfo* info = (CMGetRegMobileCodeInfo*)myResult.result;
            self.phoneCode.text = info.mobileCode;
            
        }else if(myResult.code == 1){
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];   
}

- (IBAction)doBtnClicted:(id)sender {
    
    CMCheckPwdMobileCodeParam* param = [[CMCheckPwdMobileCodeParam alloc] init];
    param.mobile = self.phoneNumber;
    param.mobileCode = self.phoneCode.text;
    CMCheckPwdMobileCodeParser* parser = [[CMCheckPwdMobileCodeParser alloc] init];
    
    [NetCenter postDataFromURL:Method_checkPwdMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            CMFReSetPasswordCtrl* reSetPWCtrl = [[CMFReSetPasswordCtrl alloc] init];
            reSetPWCtrl.phoneNum = self.phoneNumber;
            reSetPWCtrl.isModify = self.isModify;
            [self.navigationController pushViewController:reSetPWCtrl animated:YES];
        }else if(myResult.code == 1){
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
    
}

- (NSString*)getGID
{
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
    NSString *deviceId = [identifierForVendor UUIDString];
    return deviceId;
}

-(void)makeTime
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSTimeInterval timeLast = [[[NSUserDefaults standardUserDefaults] objectForKey:FORGET_CODE_TIME] longLongValue];
        
        if (timeLast <= 0)
        {
            self.reGetBtn.enabled = YES;
            [self.reGetBtn setTitle:@"重新获取" forState:UIControlStateNormal];
            [self.reGetBtn setTitle:@"重新获取" forState:UIControlStateDisabled];
            return;
        }
        
        NSTimeInterval now = [NSDate date].timeIntervalSince1970;
        if (now >= timeLast)
        {
            self.reGetBtn.enabled = YES;
            [self.reGetBtn setTitle:@"重新获取" forState:UIControlStateNormal];
            [self.reGetBtn setTitle:@"重新获取" forState:UIControlStateDisabled];
            self.reGetBtn.backgroundColor = [UIColor clearColor];
            return;
        }
        
        self.reGetBtn.enabled = NO;
        [self.reGetBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateNormal];
        [self.reGetBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateDisabled];
        [self.reGetBtn setBackgroundImage:[UIImage imageNamed:@"icon_veryCode_no"] forState:UIControlStateNormal];
        [self performSelector:@selector(makeTime) withObject:nil afterDelay:0.01];
        
    });
    
}

- (void)setTimeSynchronize{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 120] forKey:FORGET_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self setTimeSynchronize];
    [self makeTime];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(makeTime) object:nil];
}
@end
